package com.phonegap.plugins.openIDAuth;

import java.io.UnsupportedEncodingException;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.phonegap.plugins.openIDAuth.OpenIDAuth.DialogListener;

public class MyWebView extends Dialog {

    static final int FB_BLUE = 0xFF6D84B4;
    static final float[] DIMENSIONS_DIFF_LANDSCAPE = {20, 60};
    static final float[] DIMENSIONS_DIFF_PORTRAIT = {40, 60};
    static final FrameLayout.LayoutParams FILL =
        new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                         ViewGroup.LayoutParams.FILL_PARENT);
    static final int MARGIN = 4;
    static final int PADDING = 2;
    static final String DISPLAY_STRING = "touch";
    static final String FB_ICON = "icon.png";

    private String mUrl;
    private DialogListener mListener;
    private ProgressDialog mSpinner;
    private WebView mWebView;
    private LinearLayout mContent;
    private TextView mTitle;

    private String email = null;
	private String identity = null;

    public MyWebView(Context context, String url, DialogListener listener) {
        super(context);
        mUrl = url;
        mListener = listener;
    }

    private Bundle parseUrl(String completeURL) {
		Bundle parmsMap = new Bundle();
		int i = completeURL.indexOf("?");
		if (i > -1) {
			String searchURL = completeURL.substring(i + 1);
    		String params[] = searchURL.split("&");
		    for (String param : params) {
		       String temp[] = param.split("=");
		       try {
		    	   parmsMap.putString(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
		       } catch (UnsupportedEncodingException e) {
		    	   // TODO Auto-generated catch block
		    	   e.printStackTrace();
		       }
		    }
		}
	    return parmsMap;
	}
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSpinner = new ProgressDialog(getContext());
        mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSpinner.setMessage("Loading...");

        mContent = new LinearLayout(getContext());
        mContent.setOrientation(LinearLayout.VERTICAL);
        setUpTitle();
        setUpWebView();
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        final float scale = getContext().getResources().getDisplayMetrics().density;
        int orientation = getContext().getResources().getConfiguration().orientation;
        float[] dimensions =
            (orientation == Configuration.ORIENTATION_LANDSCAPE)
                    ? DIMENSIONS_DIFF_LANDSCAPE : DIMENSIONS_DIFF_PORTRAIT;
        addContentView(mContent, new LinearLayout.LayoutParams(
                display.getWidth() - ((int) (dimensions[0] * scale + 0.5f)),
                display.getHeight() - ((int) (dimensions[1] * scale + 0.5f))));
    }
    
    @Override
    protected void onStop () {
		Log.d("Google-WebView", "Webview closing");
		if (email != null && identity != null) {
			Bundle values = new Bundle();
			values.putString("email", email);
			values.putString("identity", identity);
			mListener.onComplete(values);
		}
    }

    private void setUpTitle() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mTitle = new TextView(getContext());
        mTitle.setText("Google");
        mTitle.setTextColor(Color.WHITE);
        mTitle.setTypeface(Typeface.DEFAULT_BOLD);
        mTitle.setBackgroundColor(FB_BLUE);
        mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
        mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
        mContent.addView(mTitle);
    }

    private void setUpWebView() {
        mWebView = new WebView(getContext());
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setWebViewClient(new MyWebView.MyWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl(mUrl);
        mWebView.setLayoutParams(FILL);
        mContent.addView(mWebView);
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mListener.onError(new DialogError(description, errorCode, failingUrl));
            MyWebView.this.dismiss();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("Google-WebView", "Webview loading URL: " + url);
            super.onPageStarted(view, url, favicon);
            Bundle values = parseUrl(url);
			email = values.getString("openid.ext1.value.email");
			identity = values.getString("openid.identity");
            mSpinner.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String title = mWebView.getTitle();
            if (title != null && title.length() > 0) {
                mTitle.setText(title);
            }
            mSpinner.dismiss();
            
            if (email != null && identity != null) {
            	MyWebView.this.dismiss();
            }
        }
    }
}
